package org.zwd.computePrice.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import org.zwd.computePrice.domain.CrabPrice;

public class CrabPriceDao {
	public CrabPrice loadPrice(int crabid,int isOrder){
		CrabPrice crabPrice = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			crabPrice = new CrabPrice();
			conn = DBUtils.getConnection();
			String sql = "select id,price,time,isOrder from cp_price where crabid=? and isOrder=?  order by time desc";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, crabid);
			pstmt.setInt(2, isOrder);
			rs = pstmt.executeQuery();
			
			if(rs.next()){
				crabPrice.setId(rs.getInt(1));
				crabPrice.setPrice(rs.getDouble(2));
				crabPrice.setDate(rs.getDate(3));
				crabPrice.setIsOrder(rs.getInt(4));
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		finally {
			DBUtils.free(rs, pstmt, conn);
		}
		return crabPrice;
	}
	
	
	public void insertPrice(CrabPrice crabPrice){
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			conn = DBUtils.getConnection();
			String sql = "insert into cp_price(price,time,crabid,isOrder) values(?,?,?,?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setDouble(1, crabPrice.getPrice());
			pstmt.setTimestamp(2,new Timestamp(System.currentTimeMillis()));
			pstmt.setInt(3, crabPrice.getCrabid());
			pstmt.setInt(4, crabPrice.getIsOrder());
			pstmt.executeUpdate();
		
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			DBUtils.free(null, pstmt, conn);
		}
		
	}
	
	public CrabPrice findPriceById(int id){
		CrabPrice crabPrice = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			crabPrice = new CrabPrice();
			conn = DBUtils.getConnection();
			String sql = "select id,price,time from cp_price where id = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, id);
			rs = pstmt.executeQuery();
			
			if(rs.next()){
				crabPrice.setId(rs.getInt(1));
				crabPrice.setPrice(rs.getDouble(2));
				crabPrice.setDate(rs.getDate(3));
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		finally {
			DBUtils.free(rs, pstmt, conn);
		}
		return crabPrice;
	}
}
